<!-- userList -->
<template>
	<div class="userList">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/admin/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card>
			<!-- 查询表单 -->
			<el-form
				:inline="true"
				:model="searchLinkFrom"
				:rules="searchLinkRules"
				class="demo-form-inline"
				ref="searchLinkRef"
				status-icon
				hide-required-asterisk
			>
				<el-form-item label="搜索" prop="keyword">
					<el-input
						v-model="searchLinkFrom.keyword"
						placeholder="搜索"
						size="small"
					></el-input>
				</el-form-item>
				<el-form-item label="类别" prop="class">
					<el-select v-model="searchLinkFrom.class" placeholder="类别" size="small">
						<el-option label="用户名" value="username"></el-option>
						<el-option label="手机号" value="phone"></el-option>
						<el-option label="住址" value="address"></el-option>
						<el-option label="年龄" value="age"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="small" @click="searchLinkFn('searchLinkRef')"
						>查询</el-button
					>
				</el-form-item>
				<el-form-item>
					<el-button
						type="danger"
						size="small"
						@click="searchLinkResetFn('searchLinkRef')"
						>重置</el-button
					>
				</el-form-item>
			</el-form>
			<!-- 用户表格 -->
			<el-table :data="userList.data" style="width: 100%" stripe border>
				<el-table-column prop="username" label="用户名" align="center"> </el-table-column>
				<el-table-column prop="avatar" label="头像" align="center" width="130">
					<template #default="scope">
						<el-avatar
							:size="50"
							shape="square"
							:src="scope.row.avatar ? scope.row.avatar : defaultImg"
						></el-avatar>
					</template>
				</el-table-column>
				<el-table-column prop="age" label="年龄" align="center"> </el-table-column>
				<el-table-column prop="phone" label="手机" align="center" width="130">
				</el-table-column>
				<el-table-column prop="address" label="住址" align="center" width="150">
				</el-table-column>
				<el-table-column label="是否显示" align="center">
					<template #default="scope">
						<el-switch
							v-model="scope.row.is_show"
							active-color="#13ce66"
							inactive-color="#ff4949"
							@change="editStatusFn($event, scope.row.user_id, 'is_show')"
						>
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="is_delete" label="是否删除" align="center">
					<template #default="scope">
						<el-switch
							v-model="scope.row.is_delete"
							active-color="#13ce66"
							inactive-color="#ff4949"
							@change="editStatusFn($event, scope.row.user_id, 'is_delete')"
						>
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="level" label="用户身份" align="center" width="120">
					<template #default="scope">
						<el-select
							v-model="scope.row.level"
							placeholder="请选择"
							size="mini"
							@change="editStatusFn($event, scope.row.user_id, 'level')"
						>
							<el-option
								v-for="item in levelDatas"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							>
							</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="创建时间" align="center" width="180">
					<template #default="scope">{{
						scope.row.create_time | dateFmt('YYYY-MM-DD HH:mm:ss')
					}}</template>
				</el-table-column>
				<el-table-column label="操作" width="150">
					<template #default="scope">
						<el-button size="mini" @click="handleEdit(scope.row.user_id)"
							>编辑</el-button
						>
						<el-button
							size="mini"
							type="danger"
							@click="handleDelete(scope.row.user_id)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="userList.page"
				:page-sizes="[5, 10, 15, 20]"
				:page-size="5"
				layout="total, sizes, prev, pager, next, jumper"
				:total="userList.totalSize"
			>
			</el-pagination>
		</el-card>
		<!-- 修改 -->
		<el-dialog
			:close-on-click-modal="false"
			title="修改用户"
			:visible.sync="editUserVisible"
			width="50%"
			:showClose="false"
			@close="clockHandle"
		>
			<el-form
				:model="editUserForm"
				:rules="editUserRules"
				ref="editUserRef"
				status-icon
				label-width="80px"
			>
				<el-form-item label="用户名" prop="username">
					<el-input v-model="editUserForm.username" clearable></el-input>
				</el-form-item>
				<el-form-item label="原始密码" prop="old_password">
					<el-input
						v-model="editUserForm.old_password"
						clearable
						show-password
					></el-input>
				</el-form-item>
				<el-form-item label="修改密码" prop="new_password">
					<el-input
						v-model="editUserForm.new_password"
						clearable
						show-password
					></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="editUserForm.phone" clearable type="tel"></el-input>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input v-model="editUserForm.age" clearable type="number"></el-input>
				</el-form-item>
				<el-form-item label="地址">
					<el-input v-model="editUserForm.address" clearable type="address"></el-input>
				</el-form-item>
				<el-form-item label="头像">
					<el-upload
						class="avatar-uploader"
						action="http://localhost:8000/api/utils/upload/"
						name="avatar"
						:limit="1"
						:on-success="handleAvatarSuccess"
						:on-remove="handleAvatarRemove"
						ref="avatarUploadRef"
					>
						<img
							v-if="editUserForm.avatar"
							:src="editUserForm.avatar ? editUserForm.avatar : defaultImg"
							class="avatar"
						/>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editUserVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('editUserRef')">修 改</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
//import <组件名称> from '<组件路径>';
import defaultImg from '@/assets/logo.png';
import { editStateApi, userDeleteApi, userByIdApi, UserEditApi } from '@/api/user.js';
export default {
	//数据
	data() {
		return {
			defaultImg,
			searchLinkFrom: {
				class: '',
				keyword: '',
			},
			searchLinkRules: {
				keyword: [{ required: true, message: '请输入关键字', trigger: 'blur' }],
				class: [{ required: true, message: '请选择活动区域', trigger: 'change' }],
			},
			levelDatas: [
				{
					value: '0',
					label: '普通用户',
				},
				{
					value: '1',
					label: '学生',
				},
				{
					value: '2',
					label: '老师',
				},
				{
					value: '3',
					label: '超级管理',
				},
			],
			editUserVisible: false,
			editUserForm: {
				user_id: '',
				username: '',
				old_password: '',
				new_password: '',
				phone: '',
				age: '',
				address: '',
				avatar: '',
			},
			editUserRules: {
				username: [
					{ required: true, message: '请输入用户', trigger: 'blur' },
					{ min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
				],
				old_password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
					{ min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
				],
				new_password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
					{ min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
				],
				phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
			},
		};
	},
	//计算属性
	computed: {
		userList() {
			return this.$store.state.users.userList;
		},
	},
	//侦听器
	watch: {},
	//方法
	methods: {
		// 记录列表状态
		userListStatus() {
			if (!this.userList.userListLike) {
				this.$store.dispatch('saveUserList', {
					page: this.userList.page,
					size: this.userList.size,
				});
			} else {
				this.$store.dispatch('saveUserListLike', {
					pagination: {
						page: this.userList.page,
						size: this.userList.size,
					},
					keyword: this.searchLinkFrom.keyword,
					class: this.searchLinkFrom.class,
				});
			}
		},
		// 修改用户状态
		editStatusFn(value, id, keyword) {
			editStateApi({
				value,
				id,
				keyword,
			})
				.then((d) => {
					if (d.status == 200) this.$message.success('修改成功');
				})
				.catch(() => {
					this.$message.error('修改失败');
				});
		},
		// 分页
		handleSizeChange(size) {
			// 用户列表分页
			if (!this.userList.userListLike) {
				this.$store.dispatch('saveUserList', {
					size,
					page: this.userList.page,
				});
			} else {
				// 模糊查询分页
				this.$store.dispatch('saveUserListLike', {
					pagination: { size, page: this.userList.page },
					keyword: this.searchLinkFrom.keyword,
					class: this.searchLinkFrom.class,
				});
			}
		},
		handleCurrentChange(page) {
			if (!this.userList.userListLike) {
				this.$store.dispatch('saveUserList', {
					page,
					size: this.userList.size,
				});
			} else {
				this.$store.dispatch('saveUserListLike', {
					pagination: { page, size: this.userList.size },
					keyword: this.searchLinkFrom.keyword,
					class: this.searchLinkFrom.class,
				});
			}
		},
		// 模糊查询
		searchLinkFn(formName) {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					await this.$store.dispatch('saveUserListLike', {
						pagination: {},
						...this.searchLinkFrom,
					});
					console.log(this.userList.userListLike);
					if (this.userList.userListLike.status == 'ok') {
						this.$message.success('查询成功');
					} else {
						this.$message.error('没有找到');
					}
				} else {
					// this.$message.error('请输入完整信息');
					return false;
				}
			});
		},
		// 重置模糊查询
		searchLinkResetFn(formName) {
			this.$store.dispatch('saveUserList');
			this.$refs[formName].resetFields();
		},
		// 保存上传后图片路径
		handleAvatarSuccess(response) {
			this.editUserForm.avatar = 'http://localhost:8000/' + response.data.data.path;
		},
		// 取消上传图片
		handleAvatarRemove() {
			this.editUserForm.avatar = '';
		},
		// 重置修改界面
		clockHandle() {
			// 清空上传图片
			this.$refs['avatarUploadRef'].clearFiles();
			// 清空表单
			this.$refs['editUserRef'].resetFields();
		},
		// 修改用户（查询用户并显示修改弹窗）
		async handleEdit(id) {
			let result = {};
			try {
				result = await userByIdApi(id);
			} catch (error) {
				if (!result.data.data.data) {
					return this.$message.error('用户显示状态禁用');
				} else {
					return this.$message.error('查找失败');
				}
			}
			this.editUserVisible = true;
			this.editUserForm.user_id = result.data.data.data[0].user_id;
			this.editUserForm.username = result.data.data.data[0].username;
			this.editUserForm.phone = result.data.data.data[0].phone;
			this.editUserForm.age = result.data.data.data[0].age;
			this.editUserForm.address = result.data.data.data[0].address;
			this.editUserForm.avatar =
				result.data.data.data[0].avatar != '' ? result.data.data.data[0].avatar : '';
		},
		// 提交用户修改
		submitForm(formName) {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					try {
						await UserEditApi(this.editUserForm.user_id, this.editUserForm);
					} catch (error) {
						this.$message.error(error.response.data.meta.message);
						return false;
					}
					this.editUserVisible = false;
					this.userListStatus();
				} else {
					this.$message.error('信息填写不完整');
					return false;
				}
			});
		},
		// 删除用户
		handleDelete(id) {
			this.$confirm('是否删除该用户?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					userDeleteApi(id)
						.then(() => {
							this.$message.success('删除成功!');
							this.userListStatus();
						})
						.catch(() => {
							this.$message.warning('无法删除用户');
						});
				})
				.catch(() => {
					this.$message.info('已取消删除!');
				});
		},
	},
	//生命周期 - 创建完成（可以访问当前this实例）
	created() {
		this.$store.dispatch('saveUserList');
	},
};
</script>
<style lang="less" scope></style>
